In this tutorial, we will learn how to detect browser or tab closing events using Vue.js. This functionality is useful for saving work before sessions end or alerting about unsaved changes. By utilizing this feature, it ensures that users do not lose important data and provides safeguards against accidental closures.
How to Add Window Close Event Listener in Vue Js?
In the code below, we provide a custom function to handle the beforeunload
event, which ensures that when a user tries to leave or close the tab, a popup confirmation alert is shown. If you wish to edit this code, you can use the ‘Try it’ editor.
Vue Js On Tab Close Event | Browser
<script type="module">
const app = Vue.createApp({
data() {
return {
inputValue: ''
};
},
mounted() {
window.addEventListener('beforeunload', this.handleBeforeUnload);
},
methods: {
handleBeforeUnload(event) {
event.preventDefault();
}
},
});
app.mount("#app");
</script>